const editor = document.getElementById('markdown-editor');
const preview = document.getElementById('preview');
const lineNumbers = document.getElementById('line-numbers');
let characterName = [
    "胖虎:",
    "小夫:",
    "静香:",
    "大雄:"
];

editor.addEventListener('input', () => {
    const markdownText = editor.value;
    const htmlContent = markdownToHtml(markdownText);
    preview.innerHTML = htmlContent;
    updateLineNumbers();
});

editor.addEventListener('scroll', () => {
    lineNumbers.scrollTop = editor.scrollTop;
});


function markdownToHtml(markdown) {
    let headerCount = 0;
    console.log(markdown.split('\n'));
    return markdown
        .split('\n')
        .map(line => {
            if (line.startsWith('#1 ')) {
                return `${characterName[0]}${line.slice(3)}<br>`;
            } else if (line.startsWith('#2 ')) {
                return `${characterName[1]}${line.slice(3)}<br>`;
            } else if (line.startsWith('#3 ')) {
                return `${characterName[2]}${line.slice(3)}<br>`;
            } else if (line.startsWith('#4 ')) {
                return `${characterName[3]}${line.slice(3)}<br>`;
            } else if (line.startsWith('###### ')) {
                return `<h6>${line.slice(7)}</h7>`;
            } else if (line.startsWith('##### ')) {
                return `<h5>${line.slice(6)}</h6>`;
            } else if (line.startsWith('#### ')) {
                return `<h4>${line.slice(5)}</h5>`;
            } else if (line.startsWith('### ')) {
                return `<h3>${line.slice(4)}</h4>`;
            } else if (line.startsWith('## ')) {
                return `<h2>${line.slice(3)}</h3>`;
            } else if (line.startsWith('# ')) {
                headerCount++;
                //此处应为h1，但h1在html中是默认样式行间距过大，展示易超出视图，所以用h2代替
                return `<h1>${headerCount}. ${line.slice(2)}</h2>`;
            } else {
                return line.trim() ? `${line}<br>` : '<br>';
            }
        })
        .join('');
}

// function updateLineNumbers() {
//     const lines = editor.value.split('\n').length;
//     lineNumbers.innerHTML = Array.from({ length: lines }, (_, i) => i + 1).join('<br>');
// }

// 初始化行号
// updateLineNumbers();

// 绑定输入框的值到 characterName 数组
document.querySelectorAll('.character-input').forEach((input, index) => {
    input.addEventListener('input', (event) => {
        characterName[index] = event.target.value + ':';
    });
});
